/**
 * Created by justao on 16/2/13.
 */
'use strict';

import React, {
  Component,
  NavigationExperimental,
  StyleSheet,
  View,
} from 'react-native';
const {
  RootContainer: NavigationRootContainer,
  Header: NavigationHeader,
  Container: NavigationContainer,
  Reducer: NavigationReducer,
  AnimatedView: NavigationAnimatedView,
  Card: NavigationCard,
  View: NavigationView,
} = NavigationExperimental;

import CodePush from 'react-native-code-push';

import {
    ExamplePageAction,
    ExampleSettingsPageAction,
    ExampleExitAction
} from './actions'
import {stateTypeTitleMap} from './Basic/Strings';

import TabBar from './Basic/TabBar';
import MePage from './Account/MePage';
import TalksPage from './Meetings/TalksPage';
import PlansPage from './Meetings/PlansPage';

const _jsInstanceUniqueId = '' + Date.now();
let _uniqueIdCount = 0;
function pageStateActionMap(action) {
  return {
    key: 'page-' + _jsInstanceUniqueId + '-' + (_uniqueIdCount++),
    type: action.type,
  };
}

function getTabActionMatcher(key) {
  return function (action) {
    if (!ExamplePageAction.match(action)) {
      return false;
    }
    if (ExampleSettingsPageAction.match(action)) {
      return key === 'settings';
    }
    return true;
  };
}

const MAIN_TABS = [
  {
    label: 'Talks',
    reducer: NavigationReducer.StackReducer({
      initialStates: [
        {type: 'HomePage', key: 'base'}
      ],
      key: 'Talks',
      matchAction: getTabActionMatcher('Talks'),
      actionStateMap: pageStateActionMap,
    }),
  },
  {
    label: 'Plans',
    reducer: NavigationReducer.StackReducer({
      initialStates: [
        {type: 'PlansPage', key: 'base'}
      ],
      key: 'Plans',
      matchAction: getTabActionMatcher('Plans'),
      actionStateMap: pageStateActionMap,
    }),
  },
  {
    label: 'Me',
    reducer: NavigationReducer.StackReducer({
      initialStates: [
        {type: 'MePage', key: 'base'}
      ],
      key: 'Me',
      matchAction: getTabActionMatcher('Me'),
      actionStateMap: pageStateActionMap,
    }),
  },
];

const AppReducer = NavigationReducer.TabsReducer({
  tabReducers: MAIN_TABS.map(tab => tab.reducer),
});

class MainPage extends React.Component {
  render() {
    return (
      <NavigationAnimatedView
        style={styles.tabContent}
        navigationState={this.props.navigationState}
        renderOverlay={this._renderHeader.bind(this)}
        renderScene={this._renderScene.bind(this)}
      />
    );
  }
  _renderHeader(position, layout) {
    return (
      <NavigationHeader
        navigationState={this.props.navigationState}
        position={position}
        layout={layout}
        getTitle={state => stateTypeTitleMap(state)}
      />
    );
  }
  _renderScene(child, index, position, layout) {
    var content = <View />;
    switch(child.type){
        case 'HomePage':
          content = <TalksPage />;
          break;
        case 'PlansPage':
          content = <PlansPage />;
          break;
        case 'MePage':
          content = <MePage onNavigate={this.props.onNavigate}/>;
          break;
    }
    return (
      <NavigationCard
        key={child.key}
        index={index}
        childState={child}
        navigationState={this.props.navigationState}
        position={position}
        layout={layout}>
        { content }
      </NavigationCard>
    );
  }
}
MainPage = NavigationContainer.create(MainPage);

class MainView extends React.Component {
  render() {
    return (
      <NavigationView
        navigationState={this.props.navigationState}
        style={styles.tabsContent}
        renderScene={(tabState, index) => (
          <MainPage
            key={tabState.key}
            navigationState={tabState}
            onNavigate={this._handleNavigation.bind(this, tabState.key)}
          />
        )}
      />
    );
  }
  _handleNavigation(tabKey, action) {
    if (ExampleExitAction.match(action)) {
      this.props.onExampleExit();
      return;
    }
    this.props.onNavigate(action);
  }
}
MainView = NavigationContainer.create(MainView);

export default class App extends Component {
  /*
  componentDidMount() {
    CodePush.sync({
      deploymentKey: "rdZHg4lDK9kquwJOWJ7KJc7q8ZsY4JX8VEPcg",
      updateDialog: {
        optionalIgnoreButtonLabel: '稍后',
        optionalInstallButtonLabel: '后台更新',
        optionalUpdateMessage: 'Groupers有新版本了，是否更新？',
        title: '更新提示'
      },
      installMode: CodePush.InstallMode.ON_NEXT_RESTART
    });
  }*/

  render() {
    return (
      <NavigationRootContainer
        reducer={AppReducer}
        persistenceKey="GroupersAppState"
        ref={navRootContainer => { this.navRootContainer = navRootContainer; }}
        renderNavigation={this.renderApp.bind(this)}
      />
    );
  }
  handleBackAction() {
    return (
      this.navRootContainer &&
      this.navRootContainer.handleNavigation(NavigationRootContainer.getBackAction())
    );
  }
  renderApp(navigationState, onNavigate) {
    if (!navigationState) {
      return null;
    }
    
    return (
      <View style={styles.topView}>
        <MainView
          navigationState={navigationState}
          onExampleExit={this.props.onExampleExit}
        />
        <TabBar
          tabs={navigationState.children}
          index={navigationState.index}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  topView: {
    flex: 1,
  },
  tabsContent: {
    flex: 1,
  },
  tabContent: {
    flex: 1,
  },
});